require 'mysql_api'
puts Time.now.strftime("%Y%m%d") + "_deleteAccessLogFor_18.36.0.10"

ADayLongSecond = 86400
today = Time.now
aMonthAgo = today - (31*ADayLongSecond)
monthTable = "log_"+aMonthAgo.strftime("%Y%m")
dateTable  = "log_"+aMonthAgo.strftime("%Y%m%d")
dateTables = ""
thisMonth = aMonthAgo.month
tmp = aMonthAgo + ADayLongSecond
while tmp.month == thisMonth
        dateTables += "`log_"+tmp.strftime("%Y%m%d")+"`"
        tmp = tmp + ADayLongSecond
        if tmp.month <= thisMonth
                dateTables += ","
        end
end

deleteDateTableSql = "drop table if exists #{dateTable};"
deleteMonthTableSql = "drop table if exists #{monthTable};"
createMonthTableSql =
"CREATE TABLE if not exists `#{monthTable}` (" +
"  `id` int(11) NOT NULL," +
"  `user_id` int(11) NOT NULL," +
"  `ad_id` int(11) NOT NULL," +
"  `site_id` int(11) NOT NULL," +
"  `channel_id` varchar(50) DEFAULT NULL," +
"  `mobile` varchar(50) DEFAULT NULL," +
"  `uv_tag` varchar(50) DEFAULT NULL," +
"  `ua` varchar(100) DEFAULT NULL," +
"  `ip` varchar(15) DEFAULT NULL," +
"  `referer` varchar(255) DEFAULT NULL," +
"  `txid` varchar(50) DEFAULT NULL," +
"  `remark` varchar(255) DEFAULT NULL," +
"  `type` tinyint(4) NOT NULL," +
"  `sub_type` tinyint(4) DEFAULT NULL," +
"  `access_type` tinyint(4) DEFAULT NULL," +
"  `access_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP," +
"  `mno` tinyint(4) DEFAULT NULL," +
"  KEY `id` (`id`)," +
"  KEY `time_ad_site` (`access_time`,`ad_id`,`site_id`)," +
"  KEY `mobile` (`mobile`)," +
"  KEY `referer` USING BTREE (`referer`(30))" +
") ENGINE=MRG_MyISAM DEFAULT CHARSET=utf8 UNION=(#{dateTables});"
if dateTables.length == 0
        createMonthTableSql = ""
end

#puts "delete dataTable :#{deleteDateTableSql}"
#puts "delete monthTable:#{deleteMonthTableSql}"
#puts "create monthTable:#{createMonthTableSql}"

begin
		db = Mysql.real_connect("18.36.0.10", "xxxx", "xxxx","yeahwapunion2_stat", 3306)
		if deleteDateTableSql.length > 0
			db.query(deleteDateTableSql)
			puts "#{deleteDateTableSql}, exe success !!"
		end
		if deleteMonthTableSql.length > 0
			db.query(deleteMonthTableSql)
			puts "#{deleteMonthTableSql}, exe success !!"
		end
		if createMonthTableSql.length > 0
			db.query(createMonthTableSql)
			puts "#{createMonthTableSql}, exe success !!"
		end
rescue Mysql::Error=>e
        puts "Error code:#{e.errno}"
        puts "Error message:#{e.error}"
        puts "Error SQLSTATE:#{e.sqlstate}" if e.respond_to?("sqlstate")
ensure
        db.close if db
end
